<template>
    <div id="bg">
        <div
            style="position: sticky;top: 0;text-align: center;background-color: rgba(255, 255, 255, 0.7); backdrop-filter: blur(6px);">
            GPT-3
        </div>
        <div class="msg">
            <div v-for="({ sender, content }, index) in gpt3MsgList" :key="index" style="display:flex;align-items: center;"
                :style="{ 'justify-content': sender == 'self' ? 'end' : 'start' }">
                <div style="border:1px solid;padding: 2px 5px;margin: 3px 0;border-radius: 5px;max-width: 80%;"
                    :style="{ backgroundColor: sender == 'self' ? '#D8B0FF' : '#5DFF95' }">
                    {{ content }}
                </div>
            </div>
        </div>
        <a-row style="height: 8%;padding-top: 4px;">
            <a-col :span="20">
                <a-input v-model:value="text" @keyup.enter="send" />
            </a-col>
            <a-col :span="4">
                <a-button type="primary" @click="send" style="width: 86%;float: right;" :icon="icon" />
            </a-col>
        </a-row>
    </div>
</template>

<script setup>
import { ref, watch, h } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { SendOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { useUserStore } from '@/stores/user';
const gpt3WebSocket = new WebSocket('ws://' + axios.defaults.baseURL.substring(7) + "/gpt3");
const userStore = useUserStore()
gpt3WebSocket.onopen = () => {
    ElMessage.success('GPT-3 WebSocket 连接成功')
}
const icon = ref(h(SendOutlined))
const gpt3MsgList = ref(userStore.getGPT3Histories)
const text = ref('')

gpt3WebSocket.onmessage = e => {// 监听消息
    let data = JSON.parse(e.data)
    if (data.sender == 'gpt3') {
        userStore.gpt3Histories.push(data)
        icon.value = h(SendOutlined)
        return
    }
    userStore.gpt3Histories.push(data)
}

watch(
    userStore.gpt3Histories, () => {
        // 克隆数组
        gpt3MsgList.value = userStore.getGPT3Histories
    }
)

const send = () => {
    if (text.value.length == 0) {
        return
    }
    icon.value = h(LoadingOutlined)
    gpt3WebSocket.send(
        JSON.stringify(
            {
                sender: "self",
                content: text.value
            }
        )
    );
    text.value = ''
}

</script>


<style scoped>
#bg {
    padding: 6px;
    background-color: rgb(189, 247, 207);
    border: solid;
    border-radius: 10px;
}

#bg>.msg {
    padding: 0 6px;
    height: 88%;
    overflow: auto;
    display: flex;
    flex-direction: column-reverse;
}

::-webkit-scrollbar {
    width: 2px;
}

::-webkit-scrollbar-thumb {
    background-color: rgb(49, 41, 96);
}
</style>

